﻿using System.IO;
using System.Xml;

namespace GerbilMigrate
{
    /// <summary>
    /// Internal class used to load Xml files that are embedded in the current assembly.
    /// </summary>
    internal class XmlLoader
    {
        /// <summary>
        /// Loads an embedded XML document referenced by a resource name.
        /// </summary>
        /// <param name="resourceName">Name of the resource.</param>
        /// <returns>XmlDocument object if resource exists; otherwise null</returns>
        internal static XmlDocument GetEmbeddedXmlDocument(string resourceName)
        {
            XmlDocument xml = null;

            try
            {
                using (Stream fileStream = GetEmbeddedXmlStream(resourceName))
                {
                    if (fileStream != null)
                    {
                        xml = new XmlDocument();
                        xml.Load(fileStream);
                    }
                }
            }
            catch
            {
                // if anything goes wrong I don't care - just return a null object.
            }

            return xml;
        }

        /// <summary>
        /// Loads an embedded XML document referenced by a resource name.
        /// </summary>
        /// <param name="resourceName">Name of the resource.</param>
        /// <returns>Stream for the XML document if resource exists; otherwise null</returns>
        internal static Stream GetEmbeddedXmlStream(string resourceName)
        {
            try
            {
                return typeof(XmlLoader).Assembly.GetManifestResourceStream("GerbilMigrate." + resourceName);
            }
            catch
            {
                return null;
            }
        }
    }
}
